package com.bruce.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luotuan
 * @Description  2数之和
 * @create 2020-07-10 13:49
 **/
public class SumSolution {
    public static int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        int[] subArray = new int[2];
        int sub = 0;
        List<Integer> numsList = new ArrayList<>();
        Arrays.stream(nums).forEach((num)->{
            numsList.add(num);
        });
        System.out.println(numsList.get(0));
        for(int i=0;i< length;i++){
            sub = target - nums[i];
            if(numsList.contains(sub) && (nums[i]!=sub)){
                subArray[0] = i;
                break;
            }
        }
        for(int i=0;i< length;i++){
            if(sub == nums[i]){
                subArray[1] = i;
            }
        }
        return subArray;
    }

    public static int[] twoSum2(int[] nums, int target){
        int length = nums.length;
        int[] result = new int[2];
        out:for(int i=0;i<length;i++){
            int sub = target - nums[i];
            for(int j=i+1;j<length;j++){
                if(sub == nums[j]){
                    result[0] = i;
                    result[1] = j;
                    break out;
                }
            }
        }
        return result;
    }

    public static int[] twoSum3(int[] nums, int target){
        int length = nums.length;
        int[] result = new int[2];
        Map<Integer,Integer> subMap = new HashMap<>();
        for(int i=0;i<length;i++){
            int sub = target - nums[i];
            if(subMap.containsKey(nums[i])){
                result[0] = subMap.get(nums[i]);
                result[1] = i;
                break;
            }
            subMap.put(sub,i);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1,4,2,8,10};
        int[] result = twoSum3(nums,11);
        System.out.println(Arrays.toString(result));
    }
}
